﻿using App_1.Dtos;
using App_1.Identity;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace App_1.Controllers
{
    [Route("api/account")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly UserManager<IdentityUser> _userManager;

        public AccountController(IMapper mapper, UserManager<IdentityUser> userManager)
        {
            _mapper = mapper;
            _userManager = userManager;
        }

        [HttpPost("register")]
        public async Task<IActionResult> Register(UserForRegistrationDto userDto)
        {
            var user = _mapper.Map<IdentityUser>(userDto);
            var result = await _userManager.CreateAsync(user, userDto.Password);
            if (!result.Succeeded)
            {
                return BadRequest(result.Errors);
            }

            //await _userManager.AddToRoleAsync(user, "Guest");

            return Ok();
        }


        [HttpPost("login")]
        public async Task<IActionResult> Login(UserForLoginDto userDto, [FromServices] IIdentityService identityService)
        {
            var user = await _userManager.FindByNameAsync(userDto.UserName);
            if (user is null || !await _userManager.CheckPasswordAsync(user, userDto.Password))
            {
                return Unauthorized();
            }

            var token = identityService.GetAccessToken(user);

            if (token is null) return BadRequest();

            return Ok(new { token });
        }

        [Authorize]//表示此端点受保护
        [HttpGet("test")]
        public IActionResult Test()
        {
            return Ok(new
            {
                Username = User.FindFirstValue(ClaimTypes.Name)
            });
        }
    }
}
